<template>
  <view class="qr-scanner-container">
    <view class="scanner-header">
      <text class="scanner-title">{{ title }}</text>
      <text class="scanner-subtitle">{{ subtitle }}</text>
    </view>

    <view class="scanner-content">
      <!-- 扫描区域 -->
      <view v-if="!scanResult && !error" class="scan-area">
        <!-- 相机预览区域 -->
        <view class="camera-container">
          <view class="scan-frame">
            <view class="corner corner-tl"></view>
            <view class="corner corner-tr"></view>
            <view class="corner corner-bl"></view>
            <view class="corner corner-br"></view>
            <view class="scan-line" :class="{ 'scanning': isScanning }"></view>
          </view>

          <view class="scan-tips">
            <text class="tips-text">将二维码放入框内，即可自动扫描</text>
          </view>
        </view>

        <!-- 扫描控制 -->
        <view class="scan-controls">
          <button class="scan-btn" :class="{ 'scanning': isScanning }" @click="toggleScan" :disabled="loading">
            <uni-icons :type="isScanning ? 'close' : 'scan'" size="24" color="#fff"></uni-icons>
            <text>{{ isScanning ? '停止扫描' : '开始扫描' }}</text>
          </button>

          <button class="manual-btn" @click="showManualInput" :disabled="loading">
            <uni-icons type="compose" size="20" color="#007aff"></uni-icons>
            <text>手动输入</text>
          </button>

          <button class="album-btn" @click="chooseFromAlbum" :disabled="loading">
            <uni-icons type="image" size="20" color="#007aff"></uni-icons>
            <text>从相册选择</text>
          </button>
        </view>
      </view>

      <!-- 扫描结果 -->
      <view v-if="scanResult && !error" class="scan-result">
        <view class="result-header">
          <uni-icons type="checkmarkempty" size="48" color="#52c41a"></uni-icons>
          <text class="result-title">扫描成功</text>
        </view>

        <view class="result-content">
          <view class="order-info">
            <view class="info-item">
              <text class="info-label">订单号：</text>
              <text class="info-value">{{ scanResult.orderNumber }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">金额：</text>
              <text class="info-value amount">¥{{ scanResult.finalAmount }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">状态：</text>
              <text class="info-value status" :class="statusClass">
                {{ getStatusText(scanResult.status) }}
              </text>
            </view>
            <view v-if="scanResult.User" class="info-item">
              <text class="info-label">用户：</text>
              <text class="info-value">{{ scanResult.User.nickname || scanResult.User.phone }}</text>
            </view>
          </view>

          <view class="result-actions">
            <button class="action-btn primary" @click="handleOrder" :disabled="processing">
              {{ actionButtonText }}
            </button>
            <button class="action-btn secondary" @click="resetScan" :disabled="processing">
              重新扫描
            </button>
          </view>
        </view>
      </view>

      <!-- 错误状态 -->
      <view v-if="error" class="scan-error">
        <uni-icons type="info" size="48" color="#ff5722"></uni-icons>
        <text class="error-title">扫描失败</text>
        <text class="error-message">{{ error }}</text>
        <view class="error-actions">
          <button class="retry-btn" @click="resetScan">重新扫描</button>
          <button class="manual-btn" @click="showManualInput">手动输入</button>
        </view>
      </view>

      <!-- 加载状态 -->
      <view v-if="loading" class="loading-overlay">
        <uni-load-more status="loading" :content-text="loadingText"></uni-load-more>
      </view>
    </view>

    <!-- 手动输入弹窗 -->
    <view v-if="showManualModal" class="manual-modal" @click="closeManualInput">
      <view class="manual-content" @click.stop>
        <view class="manual-header">
          <text class="manual-title">手动核销</text>
          <text class="manual-close" @click="closeManualInput">×</text>
        </view>
        <view class="manual-body">
          <view class="input-group">
            <text class="input-label">请输入订单号进行核销：</text>
            <input v-model="manualInput" class="manual-input" placeholder="请输入订单号，如：ORD20250107001" :maxlength="50" />
          </view>
        </view>
        <view class="manual-actions">
          <button class="manual-cancel" @click="closeManualInput">取消</button>
          <button class="manual-confirm" @click="processManualInput" :disabled="!manualInput.trim()">
            确定
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { verifyOrderQRCode } from '@/api/orders'

export default {
  name: 'QRScanner',
  props: {
    title: {
      type: String,
      default: '扫描订单二维码'
    },
    subtitle: {
      type: String,
      default: '请将二维码对准扫描框'
    },
    actionType: {
      type: String,
      default: 'verify', // verify: 验证, process: 处理订单
      validator: (value) => ['verify', 'process'].includes(value)
    }
  },
  data() {
    return {
      isScanning: false,
      loading: false,
      processing: false,
      error: '',
      scanResult: null,
      showManualModal: false,
      manualInput: '',
      loadingText: {
        contentdown: '处理中...',
        contentrefresh: '处理中...',
        contentnomore: '处理完成'
      }
    }
  },
  computed: {
    actionButtonText() {
      if (this.actionType === 'process') {
        return '处理订单'
      }
      return '查看详情'
    },

    // 计算状态样式类
    statusClass() {
      if (!this.scanResult || !this.scanResult.status) {
        return ''
      }
      return `status-${this.scanResult.status}`
    }
  },
  methods: {
    // 开始/停止扫描
    toggleScan() {
      if (this.isScanning) {
        this.stopScan()
      } else {
        this.startScan()
      }
    },

    // 开始扫描
    startScan() {
      // #ifdef MP-WEIXIN
      uni.scanCode({
        success: (res) => {
          console.log('扫描结果:', res)
          this.processScanResult(res.result)
        },
        fail: (error) => {
          console.error('扫描失败:', error)
          if (error.errMsg && !error.errMsg.includes('cancel')) {
            this.error = '扫描失败，请重试'
          }
        }
      })
      // #endif

      // #ifdef H5
      // H5环境下的扫描实现
      this.simulateScan()
      // #endif
    },

    // 停止扫描
    stopScan() {
      this.isScanning = false
    },

    // 模拟扫描（用于H5测试）
    simulateScan() {
      this.isScanning = true

      // 模拟扫描延迟
      setTimeout(() => {
        const mockQRData = {
          type: 'order',
          orderId: 1,
          orderNumber: 'ORD20250107001',
          token: 'mock-token-123',
          amount: 25.50,
          status: 'confirmed',
          timestamp: Date.now()
        }

        this.processScanResult(JSON.stringify(mockQRData))
        this.isScanning = false
      }, 2000)
    },

    // 处理扫描结果
    async processScanResult(result) {
      this.loading = true
      this.error = ''

      try {
        console.log('处理扫描结果:', result)

        let qrData
        try {
          // 尝试解析JSON格式的二维码数据
          qrData = JSON.parse(result)
        } catch (e) {
          // 如果不是JSON，可能是URL或纯文本
          if (result.includes('token=')) {
            // 从URL中提取token
            const urlParams = new URLSearchParams(result.split('?')[1])
            const token = urlParams.get('token')
            if (token) {
              qrData = { token }
            }
          } else {
            // 可能是订单号或其他格式
            qrData = { orderNumber: result }
          }
        }

        if (!qrData) {
          throw new Error('无效的二维码格式')
        }

        // 验证二维码
        const response = await verifyOrderQRCode(qrData)

        if (response.success) {
          this.scanResult = response.data.order
          this.$emit('scan-success', {
            qrData,
            order: response.data.order,
            verifyInfo: response.data.verifyInfo
          })
        } else {
          throw new Error(response.message || '二维码验证失败')
        }
      } catch (error) {
        console.error('处理扫描结果失败:', error)
        this.error = error.message || '处理失败，请重试'
        this.$emit('scan-error', error)
      } finally {
        this.loading = false
      }
    },

    // 从相册选择
    chooseFromAlbum() {
      uni.chooseImage({
        count: 1,
        sourceType: ['album'],
        success: (res) => {
          // 这里需要使用图片识别库来解析二维码
          // 由于uni-app限制，这里只是模拟
          uni.showToast({
            title: '功能开发中',
            icon: 'none'
          })
        },
        fail: (error) => {
          console.error('选择图片失败:', error)
        }
      })
    },

    // 显示手动输入
    showManualInput() {
      this.showManualModal = true
      this.manualInput = ''
    },

    // 关闭手动输入
    closeManualInput() {
      this.showManualModal = false
      this.manualInput = ''
    },

    // 处理手动输入
    processManualInput() {
      if (!this.manualInput.trim()) {
        uni.showToast({
          title: '请输入内容',
          icon: 'none'
        })
        return
      }

      this.closeManualInput()
      this.processScanResult(this.manualInput.trim())
    },

    // 处理订单
    async handleOrder() {
      if (!this.scanResult) return

      this.processing = true

      try {
        if (this.actionType === 'process') {
          // 处理订单逻辑
          this.$emit('order-process', this.scanResult)
        } else {
          // 查看订单详情
          this.$emit('order-detail', this.scanResult)
        }
      } catch (error) {
        console.error('处理订单失败:', error)
        uni.showToast({
          title: error.message || '处理失败',
          icon: 'none'
        })
      } finally {
        this.processing = false
      }
    },

    // 重置扫描
    resetScan() {
      this.scanResult = null
      this.error = ''
      this.isScanning = false
      this.loading = false
      this.processing = false
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        'pending': '待确认',
        'confirmed': '已确认',
        'processing': '处理中',
        'printing': '打印中',
        'completed': '已完成',
        'cancelled': '已取消'
      }
      return statusMap[status] || '未知状态'
    },

    // 获取状态样式
    getStatusClass(status) {
      return `status-${status}`
    }
  }
}
</script>

<style lang="scss" scoped>
.qr-scanner-container {
  height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.scanner-header {
  padding: 40rpx 30rpx 20rpx;
  text-align: center;
  background: #fff;

  .scanner-title {
    display: block;
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 10rpx;
  }

  .scanner-subtitle {
    display: block;
    font-size: 28rpx;
    color: #666;
  }
}

.scanner-content {
  flex: 1;
  position: relative;
  padding: 30rpx;
}

.scan-area {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.camera-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
}

.scan-frame {
  width: 500rpx;
  height: 500rpx;
  position: relative;
  border: 4rpx solid rgba(255, 255, 255, 0.3);
  border-radius: 12rpx;

  .corner {
    position: absolute;
    width: 60rpx;
    height: 60rpx;
    border: 6rpx solid #007aff;

    &.corner-tl {
      top: -6rpx;
      left: -6rpx;
      border-right: none;
      border-bottom: none;
      border-top-left-radius: 12rpx;
    }

    &.corner-tr {
      top: -6rpx;
      right: -6rpx;
      border-left: none;
      border-bottom: none;
      border-top-right-radius: 12rpx;
    }

    &.corner-bl {
      bottom: -6rpx;
      left: -6rpx;
      border-right: none;
      border-top: none;
      border-bottom-left-radius: 12rpx;
    }

    &.corner-br {
      bottom: -6rpx;
      right: -6rpx;
      border-left: none;
      border-top: none;
      border-bottom-right-radius: 12rpx;
    }
  }

  .scan-line {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4rpx;
    background: linear-gradient(90deg, transparent, #007aff, transparent);
    border-radius: 2rpx;

    &.scanning {
      animation: scan-move 2s linear infinite;
    }
  }
}

@keyframes scan-move {
  0% {
    top: 0;
  }

  50% {
    top: calc(100% - 4rpx);
  }

  100% {
    top: 0;
  }
}

.scan-tips {
  margin-top: 40rpx;

  .tips-text {
    font-size: 28rpx;
    color: #666;
    text-align: center;
  }
}

.scan-controls {
  padding: 40rpx 0;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  align-items: center;
}

.scan-btn {
  width: 300rpx;
  height: 100rpx;
  background: #007aff;
  color: #fff;
  border: none;
  border-radius: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  font-size: 32rpx;
  font-weight: bold;

  &.scanning {
    background: #ff5722;
  }

  &:disabled {
    opacity: 0.6;
  }
}

.manual-btn,
.album-btn {
  width: 200rpx;
  height: 70rpx;
  background: #fff;
  color: #007aff;
  border: 2rpx solid #007aff;
  border-radius: 35rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  font-size: 28rpx;

  &:disabled {
    opacity: 0.6;
  }
}

.scan-result {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx;
}

.result-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 40rpx;

  .result-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #52c41a;
    margin-top: 20rpx;
  }
}

.result-content {
  width: 100%;
  max-width: 600rpx;
}

.order-info {
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;

  .info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;

    &:last-child {
      margin-bottom: 0;
    }

    .info-label {
      font-size: 28rpx;
      color: #666;
    }

    .info-value {
      font-size: 28rpx;
      color: #333;
      font-weight: bold;

      &.amount {
        color: #ff5722;
        font-size: 32rpx;
      }

      &.status {
        &.status-pending {
          color: #ff9800;
        }

        &.status-confirmed {
          color: #2196f3;
        }

        &.status-processing {
          color: #9c27b0;
        }

        &.status-printing {
          color: #ff5722;
        }

        &.status-completed {
          color: #4caf50;
        }

        &.status-cancelled {
          color: #f44336;
        }
      }
    }
  }
}

.result-actions {
  display: flex;
  gap: 20rpx;

  .action-btn {
    flex: 1;
    height: 80rpx;
    border-radius: 8rpx;
    font-size: 32rpx;
    border: none;

    &.primary {
      background: #007aff;
      color: #fff;
    }

    &.secondary {
      background: #f0f0f0;
      color: #333;
    }

    &:disabled {
      opacity: 0.6;
    }
  }
}

.scan-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 40rpx;

  .error-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #ff5722;
    margin: 20rpx 0 10rpx;
  }

  .error-message {
    font-size: 28rpx;
    color: #666;
    text-align: center;
    line-height: 1.4;
    margin-bottom: 40rpx;
  }

  .error-actions {
    display: flex;
    gap: 20rpx;

    .retry-btn,
    .manual-btn {
      padding: 20rpx 40rpx;
      border-radius: 8rpx;
      font-size: 28rpx;
      border: none;
    }

    .retry-btn {
      background: #007aff;
      color: #fff;
    }

    .manual-btn {
      background: #f0f0f0;
      color: #333;
    }
  }
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
}

.manual-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.manual-content {
  background: #fff;
  border-radius: 16rpx;
  margin: 40rpx;
  max-width: 600rpx;
  width: 100%;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.manual-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;

  .manual-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }

  .manual-close {
    font-size: 48rpx;
    color: #999;
    line-height: 1;
    padding: 10rpx;
  }
}

.manual-body {
  flex: 1;
  padding: 30rpx;

  .input-group {
    .input-label {
      display: block;
      font-size: 28rpx;
      color: #333;
      margin-bottom: 20rpx;
    }

    .manual-input {
      width: 100%;
      height: 80rpx;
      padding: 0 20rpx;
      border: 2rpx solid #e0e0e0;
      border-radius: 8rpx;
      font-size: 28rpx;
      line-height: 80rpx;
      box-sizing: border-box;

      &:focus {
        border-color: #007aff;
      }
    }
  }
}

.manual-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 1rpx solid #f0f0f0;

  .manual-cancel,
  .manual-confirm {
    flex: 1;
    height: 80rpx;
    border-radius: 8rpx;
    font-size: 32rpx;
    border: none;
  }

  .manual-cancel {
    background: #f0f0f0;
    color: #333;
  }

  .manual-confirm {
    background: #007aff;
    color: #fff;

    &:disabled {
      opacity: 0.6;
    }
  }
}
</style>